<template>
  <div class="main">
    <div class="form_content">
      <NScrollbar>
        <NSpin :show="spinShow">
          <div class="content">
            <div class="topTitle">附件预览</div>

            <div class="sheet_box" v-if="fjType == 'docx'">
              <div id="container" style="width: 100%;height: 100%;"></div>
            </div>

            <div class="sheet_box" v-if="fjType == 'xlsx'">
              <div id="luckysheet" style="width: 100%;height: 100%;"></div>
            </div>

            <div class="sheet_box" v-if="fjType == 'xls'">
              <div style="margin-top: 5px;border: 1px solid #a0a0a0;overflow:auto;width: 100%;height: 100%;">
                <div v-html="excel.SheetActiveTable" style="padding: 10px 15px"></div>
              </div>
            </div>

            <div class="sheet_box" v-if="fjType == 'pdf' || fjType == 'doc'">
              <iframe :src="pageUrl" frameborder="0" style="width: 100%; height: 100%" v-if="type != 'pad'"></iframe>
              <div id="PDF" style="width: 100%; height: 100%" v-else></div>
            </div>

            <div class="sheet_box" v-if="fjType == 'txt'">
              <div style="white-space: pre-wrap">{{ txtContent }}</div>
            </div>

          </div>
        </NSpin>
      </NScrollbar>
    </div>
  </div>

  <FixedAction>
    <NSpace justify="start">
      <NButton style="width: 78px; color: #5fb17f" ghost @click="goBack">
        <template #icon>
          <img :src="VBackImg" style="width: 25rem; height: 25rem" />
        </template>
        返回
      </NButton>
    </NSpace>
  </FixedAction>
</template>
<script setup lang="ts">
import { NSpace, NButton, NScrollbar, NSpin, useMessage } from 'naive-ui'
import router from '@/router'
import { useRoute } from 'vue-router'
import { reactive, ref, watch } from 'vue'
import { useTagStore } from '@/stores/layout'
import FixedAction from '@/components/FixedAction.vue'
import { sendRequest } from '@/utils/api'
import VBackImg from '@/assets/images/back.png'
import { renderAsync } from 'docx-preview'
import axios from 'axios'
import Pdfh5 from 'pdfh5'
import 'pdfh5/css/pdfh5.css'
import LuckyExcel from 'luckyexcel'
import * as XLSX from 'xlsx'

const type = import.meta.env.VITE_TYPE
const tags = useTagStore().tags
const route = useRoute()
const message = useMessage()

// 返回
const goBack = () => {
  const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)
  tags.splice(index, 1)
  if (tags.length == 0) {
    router.push({ path: '/OA/Workbench/UserDesktop' })
  } else history.back()
}
// 处理预览效果
const excel: any = reactive({
  workbook: {}, // 数据
  sheetNames: [],// 表名称集合
  sheetNameActive: "", // 激活项
  SheetActiveTable: ""// 当前激活表格
})
const pageUrl = ref()
const fjType = ref()
const txtContent = ref()
const previewFj = async (link: string) => {
  spinShow.value = true
  const tmp = link.split('.')
  if (['xlsx'].includes(tmp[tmp.length - 1])) {
    fjType.value = 'xlsx'
    const blob = await fetch(link).then((e: any) => e.blob())
    const file = new File([blob], '无法测试')
    LuckyExcel.transformExcelToLucky(file, (exportJson: any) => {
      if (exportJson.sheets === null || !exportJson.sheets.length) return
      //@ts-ignore
      window?.luckysheet.create({
        container: 'luckysheet',
        showinfobar: false,
        lang: 'zh',
        data: exportJson.sheets,
        title: exportJson.info.name,
        userInfo: exportJson.info.name.creator
      })
    })
    spinShow.value = false
  } else if (['xls'].includes(tmp[tmp.length - 1])) {
    fjType.value = 'xls'
    pageUrl.value = link
    let xhr = new XMLHttpRequest()
    xhr.open('get', link, true)
    xhr.responseType = 'arraybuffer'
    xhr.onload = function () {
      if (xhr.status === 200) {
        const data = new Uint8Array(xhr.response)
        const workbook = XLSX.read(data, { type: 'array' })
        const sheetNames = workbook.SheetNames
        excel.workbook = workbook
        excel.sheetNames = sheetNames
        excel.sheetNameActive = sheetNames[0]
        try {
          const worksheet = excel.workbook.Sheets[sheetNames[0]]
          let htmlData = XLSX.utils.sheet_to_html(worksheet, { header: '', footer: '' })
          htmlData = htmlData === '' ? htmlData : htmlData.replace(/<table/, '<table class="default-table" border="1px solid #ccc" cellpadding="0" cellspacing="0"')
          htmlData = htmlData === '' ? htmlData : htmlData.replace(/<tr/, '<tr style="background:#b4c9e8"')
          excel.SheetActiveTable = htmlData
        } catch (e) {
          excel.SheetActiveTable = '<h4 style="text-align: center">' + '暂无内容' + '</h4>'
        }
      } else if (xhr.status === 404) {
        excel.SheetActiveTable = '<h4 style="text-align: center">' + '暂无内容' + '</h4>'
      } else {
        excel.SheetActiveTable = '<h4 style="text-align: center">' + '暂无内容' + '</h4>'
      }
    }
    xhr.onerror = function () {
      excel.SheetActiveTable = '<h4 style="text-align: center">' + '暂无内容' + '</h4>'
    }
    xhr.send()
    spinShow.value = false
  } else if (['docx'].includes(tmp[tmp.length - 1])) {
    fjType.value = 'docx'
    const buffer = await fetch(link).then((e: any) => e.blob())
    const container: any = document.getElementById('container')
    const tmp = {
      className: 'docx',
      inWrapper: true,
      ignoreWidth: false,
      ignoreHeight: false,
      ignoreFonts: false,
      breakPages: true,
      ignoreLastRenderedPageBreak: true,
      experimental: false,
      trimXmlDeclaration: true,
      debug: false
    }
    renderAsync(buffer, container, undefined, tmp).then(() => { spinShow.value = false })
  } else if (['pdf'].includes(tmp[tmp.length - 1])) {
    fjType.value = 'pdf'
    if (type != 'pad') pageUrl.value = link
    else setTimeout(() => { new Pdfh5('#PDF', { pdfurl: link }) }, 500)
    spinShow.value = false
  } else if (['doc'].includes(tmp[tmp.length - 1])) {
    fjType.value = 'doc'
    // const url: any = await getDocToPdf(link)
    // if (type != 'pad') pageUrl.value = url
    // else setTimeout(() => { new Pdfh5('#PDF', { pdfurl: url }) }, 500)
    spinShow.value = false
  } else if (['txt'].includes(tmp[tmp.length - 1])) {
    fjType.value = 'txt'
    axios.get(link, { responseType: 'text' }).then((res) => { txtContent.value = res.data || '当前文件暂无数据' })
    spinShow.value = false
  } else {
    fjType.value = 'other'
    spinShow.value = false
    message.error('暂不支持该类型预览功能')
  }
}
// 获取详情
const spinShow = ref(false)
const getFJInfo = async () => {
  spinShow.value = true
  const [error, res] = await sendRequest({
    module: 'receiveOrDispatch',
    api: 'fjInfo',
    uri: {
      id: route.query.id as never
    }
  })
  if (error) return
  if (res.code !== 0) return
  await previewFj(res.data.path)
}
// doc转pdf
const getDocToPdf = async (link: any) => {
  spinShow.value = true
  const [error, res] = await sendRequest({
    module: 'receiveOrDispatch',
    api: 'docToPdf',
    override: {
      data: {
        url: link
      }
    }
  })
  if (error) return
  return res
}

watch(
  () => route,
  () => {
    if (route.path == '/OA/Common/AttachContent' && route.query.id) getFJInfo()
  },
  { deep: true, immediate: true }
)
</script>
<style scoped lang="scss">
@mixin CommonFont {
  font-size: 18rem;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: #333333;
}

.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;

  .form_content {
    width: 100%;
    height: 100%;
    padding: 20rem 20rem 0;

    .topTitle {
      font-size: 22px;
      font-family: PingFangSC, PingFang SC;
      font-weight: 500;
      color: #5fb17f;
      margin-bottom: 10rem;
    }

    .content {
      display: flex;
      flex-direction: column;
      width: 100%;
      height: 100%;
      padding: 18rem 33rem 120rem;
      overflow-y: scroll;
      background-color: #ebeceb;
      @include CommonFont;
    }
  }
}

:deep(.docx-wrapper) {
  background-color: transparent;
  padding: 20px 20px;
}

.sheet_box {
  width: 100%;
  height: calc(100vh - 300px);
}

.content::-webkit-scrollbar {
  display: none;
}

:deep(.n-spin-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-spin-content) {
  width: 100%;
  height: 100%;
}

.view-pdf {
  width: 100%;
  height: 100vh;
}
</style>
<style>
table.default-table {
  width: 100%;
  border: solid #333;
  border-width: 1px 0px 0px 1px;
  font-size: 16px;
  border-collapse: collapse;
  border-spacing: 0;
}

table.default-table tbody tr {
  height: 20px;
  line-height: 20px;
  white-space: nowrap;
}

table.default-table tbody tr:hover {
  background-color: #eee;
}

table.default-table tbody tr th,
table.default-table tbody tr td {
  padding: 3px 5px;
  text-align: left;
  border: solid #333;
  border-width: 0px 1px 1px 0px;
  white-space: nowrap;
}

table.default-table tbody tr th {
  font-weight: bold;
  text-align: center;
}

table.default-table tbody tr td a:hover {
  color: #0080c0;
}
</style>